package dao_sys

import (
	"wrblog-api-go/app/model"
	"wrblog-api-go/app/model/model_sys"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mysql"
	"wrblog-api-go/pkg/utils"
)

func GetDictDataPageList(sysDictData model_sys.SelectSysDictData) (sysDictDatas []model_sys.SysDictDataVo, total int64, err error) {
	db := mysql.Db().Model(&model_sys.SysDictDataPo{})
	if sysDictData.DictLabel != "" {
		db = db.Where("dict_label like ?", "%"+sysDictData.DictLabel+"%")
	}
	if sysDictData.DictType != "" {
		db = db.Where("dict_type = ?", sysDictData.DictType)
	}
	if sysDictData.Status != "" {
		db = db.Where("status = ?", sysDictData.Status)
	}
	if !sysDictData.StartTime.IsZero() {
		db = db.Where("create_time >= ?", sysDictData.StartTime)
	}
	if !sysDictData.EndTime.IsZero() {
		db = db.Where("create_time <= ?", sysDictData.EndTime)
	}
	db = db.Where("deleted = '0'").Count(&total).Order("dict_sort").Order("create_time desc")
	if sysDictData.PageNum != nil && sysDictData.PageSize != nil {
		db = db.Limit(*sysDictData.PageSize).Offset((*sysDictData.PageNum - 1) * *sysDictData.PageSize)
	} else {
		db = db.Limit(10)
	}
	err = db.Find(&sysDictDatas).Error
	err = errs.ErrNotFound(err)
	return
}

func ApiDictDataByType(dictType string) (sysDictDatas []*model_sys.SysDictDataVo, err error) {
	db := mysql.Db().Model(&model_sys.SysDictDataPo{})
	db.Where("deleted = '0' and dict_type = ?", dictType).Order("dict_sort")
	err = db.Find(&sysDictDatas).Error
	err = errs.ErrNotFound(err)
	return
}

func GetDictDataById(dictCode int) (sysDictData model_sys.SysDictDataVo, err error) {
	db := mysql.Db().Model(&model_sys.SysDictDataPo{})
	err = db.Where("dict_code = ? and deleted = '0'", dictCode).First(&sysDictData).Error
	err = errs.ErrNotFound(err)
	return
}

func AddDictData(sysDictData model_sys.SysDictDataPo) (int, error) {
	err := mysql.Db().Create(&sysDictData).Error
	return sysDictData.DictCode, errs.ErrNotFound(err)
}

func EditDictData(sysDictData model_sys.SysDictDataPo) (int64, error) {
	res := mysql.Db().Updates(&sysDictData)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func RemoveDictData(dictCodes []string, uk string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysDictDataPo{})
	db.Where("dict_code in (?)", dictCodes)
	res := db.Updates(&model_sys.SysDictDataPo{BaseEntity: model.BaseEntity{UpdateTime: utils.NewTimeNow(), UpdateBy: uk, Deleted: "1"}})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func DeleteDictData(dictCodes []string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysDictDataPo{})
	res := db.Delete(&model_sys.SysDictDataPo{}, dictCodes)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}
